<template>
  <div class="page">
    <div class="bind-heard">
      <el-image style="width: 150px; height: 44px" :src="leftUrl" @click="handleHome" fit="fill" class="logo" />
    </div>
    <div class="bind-card">
      <div class="bind-box create-box" v-if="bindOrCreate == 'create'">
        <p class="title">创建账号</p>
        <p class="notic">尊敬的华为用户，这是您首次登录华为云，您需要完善信息并同意相关协议声明以完成业务激活。<span>绑定账号</span></p>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm" status-icon size="default">
          <el-form-item prop="domain_name">
            <el-input v-model.trim="ruleForm.domain_name" maxlength="32" placeholder="请设置您的账号名" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="ruleForm.password" placeholder="请设置您的密码" clearable />
          </el-form-item>
          <el-form-item prop="mobile_phone">
            <el-input v-model="ruleForm.mobile_phone" placeholder="请输入您的电话号码" clearable maxlength="11" />
          </el-form-item>
          <el-form-item prop="verification_code">
            <div class="code">
              <el-input v-model="ruleForm.verification_code" placeholder="请输入短信验证码" clearable>
                <template #append>
                  <el-button style="margin-left: 10px;" @click="getCode">{{ sendText }}</el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="name">
            <label class="checkBox">
              <el-checkbox v-model="isCheeck" size="large" class="check" />
              我已阅读并同意
              <a class="term" :href="item.url" target="_blank" v-for="item in agreementsList" :key="item.id">{{ item.name
              }}</a>
            </label>
          </el-form-item>
          <el-form-item prop="name">
            <el-button :type="isCheeck ? 'danger' : 'info'" style="width: 100%;height: 40px;margin-top: 10px;"
              :disabled="isCheeck ? false : true" @click="submitForm(ruleFormRef)">绑定账号</el-button>
          </el-form-item>

        </el-form>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { createSubCustomer, sendVerificationMessageCode } from '@/api/product/index';
import type { FormInstance, FormRules } from 'element-plus';
import { getAssetURL } from "@/utils/load_assets";
import { ElForm, ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();

const leftUrl = getAssetURL("common/logo.png");
const isCheeck = ref(false);//协议阅读
const bindOrCreate = ref('create');//绑定或者创建
const ruleForm = ref<any>({});
const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  password: string,
  domain_name: string
  mobile_phone?: string
}
const rules = reactive<FormRules<RuleForm>>({
  domain_name: [
    { required: true, message: '必须输入账号名', trigger: 'blur' },
    { min: 5, max: 32, message: '账号名长度为5-32位', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        return Number.isNaN(Number(value));
      },
      message: "账号名必须为5-32位且不能全为数字",
      trigger: 'blur',
    }
  ],
  password: [
    { required: true, message: '必须输入密码', trigger: 'blur' },
    { min: 8, max: 32, message: '账号名长度为8-32位', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        return !(ruleForm.value.domain_name == value || ruleForm.value.domain_name?.split('').reverse().join('') == value);
      },
      message: "不能和账号名或倒序的账号名相同",
      trigger: 'blur',
    },{
      // 不能包含手机号
      validator: (rule, value) => {
        return !(/1[3456789]\d{9}/.test(value));
      },
      message: "不能包含手机号",
      trigger: 'blur',
    },
    {
      validator: (rule, value) => {
        let num = 0;
        if (/(?=(.*[A-Z]){1,})/.test(value)) num++;
        if (/(?=(.*[a-z]){1,})/.test(value)) num++;
        if (/(?=(.*\d){1,})/.test(value)) num++;
        if (/(?=(.*[\W_]){1,})/.test(value)) num++;
        return num >= 2;
      },
      message: "至少包含以下四种字符中的两种:大写字母、小写字母、数字、特殊字符",
      trigger: 'blur',

    }
  ],
  mobile_phone: [
    {
      pattern:  /^1[3456789]\d{9}$/,
      message: "必须是正确的手机号格式",
      trigger: "change",
    },
  ]
});

const agreementsList = ref([
  { id: '1', url: 'https://id1.cloud.huawei.com/AMW/portal/agreements/userAgreement/zh-cn_userAgreement.html', name: '《华为帐号用户协议》' },
  { id: '2', url: 'https://id1.cloud.huawei.com/AMW/portal/agreements/accPrivacyStatement/zh-cn_accPrivacyStatement.html', name: '《关于华为帐号与隐私的声明》' }
])

const hwUrl = ref('');//跳转华为云链接
const isFirstLogin = ref(false);//华为云参数
const xAccountType = ref<any>('');//华为云参数
const toUrl = ref<any>('');
const sendText = ref("获取验证码");

onMounted(() => {
  xAccountType.value = route.query.xAccountType;
  toUrl.value = route.query.toUrl;
  hwUrl.value = `https://auth.huaweicloud.com/authui/saml/login?xAccountType=${xAccountType.value}&isFirstLogin=${isFirstLogin.value}&service=` + encodeURIComponent(toUrl.value)
});

/**获取验证码 */
const getCode = () => {
  if (ruleForm.value.mobile_phone == "") {
    ElMessage.error("请输入手机号！");
    return;
  }
  if (!/^1[3456789]\d{9}$/.test(ruleForm.value.mobile_phone)) {
    ElMessage.error("请输入正确的手机号！");
    return;
  }
  if (sendText.value != "获取验证码") {
    return;
  }
  let data = {
    body: {
      body: {
        receiver_type: 1,
        timeout: 3000,
        mobile_phone: ruleForm.value.mobile_phone,
        lang: 'zh-cn',
        scene: 29
      }
    }
  }
  sendVerificationMessageCode(data).then((res: any) => {
    if (200 == res.status) {
      ElMessage.success("短信发送成功！");
      let count = 60;
      let timer = setInterval(() => {
        sendText.value = count + "秒后重新获取";
        count--;
        if (count == 0) {
          sendText.value = "获取验证码";
          clearInterval(timer);
        }
      }, 1000);
    }
  })
};

/**创建华为新用户 */
const isCreate = () => {
  if (ruleForm.value.mobile_phone) {
    if (!ruleForm.value.verification_code) {
      ElMessage.error("必须输入短信验证码！");
      return
    }
  }
  let data = {
    body: {
      body: ruleForm.value
    }
  };
  createSubCustomer(data).then((res: any) => {
    if (200 === res.code) {
      window.location.href = hwUrl.value;
    }
  })
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      isCreate();
    }
  })
}

/**跳转首页*/
const handleHome = () => {
  router.push("/client/home");
};
</script>

<style scoped lang="less">
.page {
  background-color: #fff;
}

.bind-heard {
  width: 100vw;
  height: 10vh;
  display: flex;
  align-items: center;

  .logo {
    cursor: pointer;
  }
}

.bind-card {
  width: 70vw;
  height: 80vh;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  border: 1px solid #ccc;
  box-shadow: 0 2px 5px #e4e4e4;

  .bind-box {
    width: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 50px;

    .term {
      cursor: pointer;
      color: blue;
    }

    .title {
      font-size: 26px;
      margin-bottom: 20px;
    }

    .notic {
      margin-bottom: 50px;
    }

    .code {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-top: 20px;
    }

    .checkBox {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .check {
        margin-right: 10px;
      }

    }
  }

  .create-box {
    width: 500px;
  }
}
</style>